package com.xxxx.seckill.service_impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.seckill.mapper.UserMapper;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IUserService;
import com.xxxx.seckill.utils.CookieUtil;
import com.xxxx.seckill.utils.MD5Util;
import com.xxxx.seckill.utils.UUIDUtil;
import com.xxxx.seckill.utils.ValidatorUtil;
import com.xxxx.seckill.vo.Loginvo;
import com.xxxx.seckill.vo.RespBean;
import com.xxxx.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author macaber
 * @since 2021-09-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public RespBean doLogin(Loginvo loginvo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginvo.getMobile ( );
        String password = loginvo.getPassword ( );
//        if (StringUtils.isEmpty (mobile)||StringUtils.isEmpty (password)){
//            return RespBean.error (RespBeanEnum.LOGIN_ERROR);
//        }
//        if (ValidatorUtil.isMobile (mobile)==false){
//            return RespBean.error (RespBeanEnum.MOBILE_ERROR);
//        }
        User user = userMapper.selectById (mobile);
        if (user==null){
            return RespBean.error (RespBeanEnum.LOGIN_ERROR);
        }
        if (!MD5Util.formPassToDBPass (password,user.getSlat ()).equals (user.getPassword ())){
            return RespBean.error (RespBeanEnum.LOGIN_ERROR);
        }


        String uuid = UUIDUtil.uuid ( );
        redisTemplate.opsForValue ().set ("user:"+uuid,user);

//        request.getSession ().setAttribute (uuid,user);
        CookieUtil.setCookie (request,response,"userUUID",uuid);
        return RespBean.success (uuid);
    }

    @Override
    public User getUserByCookie(String userUUID) {
        if (StringUtils.isEmpty (userUUID)){
            return null;
        }
        User user =(User) redisTemplate.opsForValue ( ).get ("user:" + userUUID);
        return user;
    }
}
